<?php


namespace app\index\controller;


use app\common\controller\IndexBase;
use app\common\model\Manager;

class Reward extends IndexBase
{
    protected function _initialize()
    {
        parent::_initialize();
        $manager = new Manager();
        $manage_info = $manager->find(3);
        if(!in_array(session('user_info')['userid'],json_decode($manage_info['list'],true))){
            $this->error('权限不足');
        }
    }

    public function index()
    {
        $status = input('status') ? input('status') : 0;
        $list = model('reward')
            ->alias('r')
            ->field('r.*,j.title')
            ->where(['r.status' => $status])
            ->join('jdz j', 'j.id=r.jdz_id')
            ->select();
        $this->assign('list', $list);
        $this->assign('status', $status);
        return $this->fetch();
    }

    public function detail()
    {
        $jdz_id = input('jdz_id');
        $info = model('reward')->where(['jdz_id' => $jdz_id])->find();
        $jdz_info = model('jdz')->find($jdz_id);
        $this->assign('info', $info);
        $this->assign('jdz_info', $jdz_info);
        return $this->fetch();

    }

    public function reward()
    {
        $jdz_id = input('jdz_id');
        $money = input('money');
        $status = input('status');
        $info = model('reward')->where(['jdz_id' => $jdz_id])->find();
        if ($info['status'] == 1) {
            return ajax_return(0, '该提议已经发放了红包，无法在进行操作了');
        }
        if ($status == 1) {
            //发红包  todo

            //记日志
            $save_data['user_id'] = $info['user_id'];
            $save_data['amount'] = $money;
            $save_data['add_time'] = time();
            $save_data['admin_user'] = session('user_info')['userid'];
            $save_data['user_name'] = get_user_info($info['user_id'])['name'];
            $save_data['relation_id'] = $jdz_id;
            if (model('reward')->isUpdate(true)->save(['status' => 1, 'money' => $money,'send_time'=>date('Y-m-d H:i:s')], ['jdz_id' => $jdz_id]) !== false) {
                if (db('useramount')->insert($save_data) !== false) {
                    model('user')->where(['user_id' => $info['user_id']])->setInc('amount', $money);
                    model('jdz')->where(['id' => $jdz_id])->setInc('reward', $money);
                }
                return ajax_return(1, '发放成功');
            } else {
                return ajax_return(0, '发放失败');
            }
        }

        if ($status == 2) {
            if (model('reward')->isUpdate(true)->save(['status' => 2], ['jdz_id' => $jdz_id]) !== false) {
                return ajax_return(1, '操作成功');
            } else {
                return ajax_return(0, '操作失败');
            }
        }
    }
}